package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.web.domain.BaseEntity;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.product.api.domain.vo.SkuQuery;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 */
@Slf4j
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    //@Autowired
    //private StringRedisTemplate stringRedisTemplate; //适合 key和value都是字符串类型

    @Autowired
    private RedisTemplate redisTemplate; //适合值是任意类型

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    //原子性
    @Override
    public int insertProduct(Product product) {
        //1.保存Product对象到product表
        productMapper.insert(product); //主键回填

        //2.保存List<ProductSku>对象到product_sku表
        List<ProductSku> productSkuList = product.getProductSkuList();
        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        int size = productSkuList.size();
        for (int i = 0; i < size; i++) {
            ProductSku productSku = productSkuList.get(i);
            productSku.setSkuCode(product.getId() + "_" + i);
            productSku.setSkuName(product.getName() + " " + productSku.getSkuSpec());
            productSku.setProductId(product.getId());
            productSkuMapper.insert(productSku);

            //添加商品库存  //3.保存List<SkuStock>对象到sku_stock表
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }

        //4.保存ProductDetails对象到product_details表
        ProductDetails productDetails = new ProductDetails();
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetails.setProductId(product.getId());
        productDetailsMapper.insert(productDetails);

        return 1;
    }


    @Override
    public Product selectProductById(Long id) {
        //1.根据id查询Product对象
        Product product = productMapper.selectById(id);

        //2.封装扩展字段：查询商品对应多个List<ProductSku>
        //select * from product_sku where product_id =?
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
        List<Long> productSkuIdList = productSkuList.stream().map(productSku -> productSku.getId()).toList();


        // select * from sku_stock where sku_id in (1,2,3,4,5,6)
        List<SkuStock> skuStockList = skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        Map<Long, Integer> skuIdToTatalNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(productSku -> {
            //返回ProductSku对象，携带了库存数据；
            productSku.setStockNum(skuIdToTatalNumMap.get(productSku.getId()));
        });

        product.setProductSkuList(productSkuList);

        //3.封装扩展字段：商品详情图片List<String>
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        String imageUrls = productDetails.getImageUrls();   //url,url,url
        String[] urls = imageUrls.split(",");
        product.setDetailsImageUrlList(Arrays.asList(urls));
        //返回Product对象
        return product;
    }


    @Override
    public int updateProduct(Product product) {
        List<ProductSku> productSkuList = product.getProductSkuList();
        List<Long> ProductIdlist = productSkuList.stream().map(ProductSku::getId).toList();
        for (Long aLong : ProductIdlist) {
            String ProductSkuId = "product:sku:" + aLong;
            redisTemplate.delete(ProductSkuId);
        }

        //1.更新Product
        productMapper.updateById(product);

        //2.更新SKU   List<ProductSku>

        if (CollectionUtils.isEmpty(productSkuList)) {
            throw new ServiceException("SKU数据为空");
        }
        productSkuList.forEach(productSku -> {
            productSkuMapper.updateById(productSku);

            //3.更新库存   List<ProductSku> -> 获取扩展字段stockNum
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setAvailableNum(skuStock.getTotalNum() - skuStock.getLockNum());
            skuStockMapper.updateById(skuStock);
        });

        //4.更新详情ProductDetails
        ProductDetails productDetails = productDetailsMapper
                .selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (Long aLong : ProductIdlist) {
            String ProductId = "product:sku:" + aLong;
            redisTemplate.delete(ProductId);
        }

        return 1;
    }


    @Override
    public int deleteProductByIds(Long[] ids) {
        //1.删除Product表数据
        // delete from product where id in (1,2)
        productMapper.deleteBatchIds(Arrays.asList(ids));

        //2.删除ProductSku表数据
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, Arrays.asList(ids)));
        List<Long> productSkuIdList = productSkuList.stream().map(ProductSku::getId).toList();
        productSkuMapper.deleteBatchIds(productSkuIdList);

        //3.删除SkuStock表数据
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, productSkuIdList));

        //4.删除ProductDetails表数据
        // delete from product_details where product_id in (1,2)
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, Arrays.asList(ids)));
        return 1;
    }


    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setId(id);
        if (auditStatus == 1) {
            product.setAuditStatus(1);
            product.setAuditMessage("审批通过");
        } else {
            product.setAuditStatus(-1);
            product.setAuditMessage("审批拒绝");
        }
        productMapper.updateById(product);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        if (status == 1) {
            product.setStatus(1);
            String key = "sku:product:data";
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, id));
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), true);
            });

            ProductSku productSku = new ProductSku();
            productSku.setStatus(1);
            productSkuMapper.update(productSku, new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId, id));

        } else {
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getStatus, 1).eq(ProductSku::getId, id));
            if (productSkuList != null) {
                String key = "sku:product:data";
                productSkuList.forEach(item -> {
                    redisTemplate.opsForValue().setBit(key, item.getId(), false);
                    String dataKey = "product:sku:" + item.getId();
                    redisTemplate.delete(dataKey);
                });
            }
            ProductSku productSku = new ProductSku();
            productSku.setStatus(-1);
            productSkuMapper.update(productSku, new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId, id));


            product.setStatus(-1);
        }
        productMapper.updateById(product);
    }


    @Override
    public List<ProductSku> getTopSale() {
        return productSkuMapper.getTopSale();
    }


    @Override
    public List<ProductSku> skuList(SkuQuery skuQuery) {
        return productSkuMapper.skuList(skuQuery);
    }


    /**
     * 服务提供者：6个接口来服务于商品详情查询。需要进行优化，提供查询效率。
     * 需要使用redis来提高性能。
     */

    @Override
    public ProductSku getProductSku(Long skuId) {
        try {
            //尝试从redis中获取结果
            String productkey = "product:sku:" + skuId;
            ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(productkey);
            //获取成功 返回结果
            if (productSku != null) {
                log.info("命中缓存，直接返回结果" + Thread.currentThread().getId() + "," + Thread.currentThread().getName());
                return productSku;
            }
            //尝试获取分布式锁
            String productKeyLock = "product:sku:lock" + skuId;
            String productKeyValue = UUID.randomUUID().toString().replaceAll("-", "");
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(productKeyLock, productKeyValue, 5, TimeUnit.SECONDS);
            //成功获取锁
            if (flag) {
                log.info("成功拿到锁，将查询数据库并放入redis" + Thread.currentThread().getId() + "," + Thread.currentThread().getName());
                try {
                    //查询数据库并将结果放入缓存
                    productSku = this.getProductSkuFromDb(skuId);
                    //判断查询结果是否为空 确定缓存时间
                    long ttl = productSku == null ? 1 * 60 : 10 * 60;
                    //放入缓存
                    redisTemplate.opsForValue().set(productkey, productKeyValue, ttl, TimeUnit.SECONDS);
                    //返回结果
                    return productSku;
                } finally {
                    //业务执行完释放锁
                    String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                            "then\n" +
                            "    return redis.call(\"del\",KEYS[1])\n" +
                            "else\n" +
                            "    return 0\n" +
                            "end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                    redisScript.setScriptText(script);
                    redisScript.setResultType(Long.class);
                    redisTemplate.execute(redisScript, Arrays.asList(productKeyLock), productKeyValue);
                }
            } else {
                //没有获取锁 自旋等待
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                log.info("线程获取锁失败，自旋等待" + Thread.currentThread().getId() + ":" + Thread.currentThread().getName());
                return this.getProductSku(skuId);
            }
        } catch (Exception e) {
            //兜底处理方案：Redis服务有问题，将业务数据获取自动从数据库获取
            log.error("[商品服务]查询商品信息异常：{}", e, "," + Thread.currentThread().getId() + "," + Thread.currentThread().getName());
            return this.getProductSkuFromDb(skuId);
        }
    }

    public ProductSku getProductSkuFromDb(Long skuId) {
        return productSkuMapper.selectById(skuId);
    }


    @Override
    public Product getProduct(Long id) {
        return productMapper.selectById(id);
    }


    @Override
    public SkuPrice getSkuPrice(Long skuId) {
        ProductSku productSku = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getId, skuId).select(ProductSku::getSalePrice, ProductSku::getMarketPrice));
        SkuPrice skuPrice = new SkuPrice();
        BeanUtils.copyProperties(productSku, skuPrice);
        return skuPrice;
    }


    @Override
    public ProductDetails getProductDetails(Long id) {
        return productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
    }


    @Override
    public Map<String, Long> getSkuSpecValue(Long id) {
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id).select(ProductSku::getId, ProductSku::getSkuSpec));
        Map<String, Long> skuSpecValueMap = new HashMap<>();
        productSkuList.forEach(item -> {
            skuSpecValueMap.put(item.getSkuSpec(), item.getId());
        });
        return skuSpecValueMap;
    }


    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuId));
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        return skuStockVo;
    }


    // select * from product_sku where id in (1,2,3)
    // select id,sale_price,market_price from product_sku where id in (1,2,3)
    @Override
    public List<SkuPrice> getSkuPriceList(List<Long> skuIdList) {
        if (CollectionUtils.isEmpty(skuIdList)) {
            return new ArrayList<SkuPrice>();
        }
        List<ProductSku> skuList = productSkuMapper
                .selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getId, skuIdList)
                        .select(ProductSku::getId, ProductSku::getSalePrice, ProductSku::getMarketPrice));
        if (CollectionUtils.isEmpty(skuList)) {
            return new ArrayList<SkuPrice>();
        }
        return skuList.stream().map((sku) -> {
            SkuPrice skuPrice = new SkuPrice();
            skuPrice.setSkuId(sku.getId());
            skuPrice.setSalePrice(sku.getSalePrice());
            skuPrice.setMarketPrice(sku.getMarketPrice());
            return skuPrice;
        }).toList();
    }

    /**
     * 作业：检查与锁定库存能否一步完成。
     * update sku_stock
     * set available_num = available_num - 5 , lock_num = lock_num +5
     * where id = 20 and available_num > 5
     *
     * @param orderNo       订单号
     * @param skuLockVoList 需要锁定库存商品信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        //1.检查传入的列表是否为空
        if (CollectionUtils.isEmpty(skuLockVoList)) {
            return "参数为空";
        }
        //OpenFeign远程调用，可能会进行重试，需要进行去重处理（使用redis setnx 设置共享标记  分布式锁）
        String Key = "sku:checkAndLock:" + orderNo;
        //业务完成，需要将锁定的数据保存到redis中时用到的key
        String dataKey = "sku:lock:data" + orderNo;
        //防止重复请求
        Boolean orderInfo = redisTemplate.opsForValue().setIfAbsent(Key, orderNo, 1, TimeUnit.HOURS);
        //没拿到锁标记，说明当前锁定业务已经完成，那么，1个小时内进行重试，不允许； 当前线程真正执行检查锁定库存业务；另一个线程过来重试，不允许。
        if (!orderInfo) {
            if (redisTemplate.hasKey(Key)) {  //说明业务已经完成，不能重试，直接返回成功。 如果存在，则已执行过库存锁定
                return "";
            } else {
                return "正在锁定库存，无法重试";
            }
        }
        //1.检查库存够不够 遍历所有商品，验库存并锁库存，要具备原子性
        StringBuilder stringBuilder = new StringBuilder("");
        for (SkuLockVo skuLockVo : skuLockVoList) {
            // 检验库存：查询，返回的是满足要求的库存列表
            int updateNum = skuStockMapper.updateStock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
//            SkuStock check = skuStockMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
//            SkuStock skuStock1 = skuStockMapper.selectById(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuLockVo.getSkuId()).ge(SkuStock::getAvailableNum, skuLockVo.getSkuNum()));

            //如果没有一个商品满足要求，这里就验库存失败
//            if (check==null) { //库存不够,告诉用户哪个商品库存不够。
//                stringBuilder.append("商品："+skuLockVo.getSkuId()+"库存不足");  // for update  增加数据库行锁，不允许其他业务来动锁定的数据。
//            }
            if (updateNum == 0) {
                throw new ServiceException("商品：" + skuLockVo.getSkuId() + "库存不足"); //事务回滚
            }
        }
//        //2.不够,锁定库存失败
//        if (StringUtils.hasText(stringBuilder.toString())) { //说明检查库存失败，存在商品库存不够情况
//             redisTemplate.delete(Key); //??????  删除，这样openfeign才可以进行重试。
//             return "商品库存不足";  // 分布式锁不解除。    正常返回字符串，事务正常提交，for update行数自动释放。
//        }
//        //3.库存够用，锁定库存成功
//        for (SkuLockVo skuLockVo : skuLockVoList) {
//            int lock = skuStockMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
//            if (lock==0) { //count表示sql语句起作用的行数。为0表示锁定库存失败
//                throw new SecurityException("商品锁定失败"); //事务回滚
//            }
//        }
        //4.把锁定数据保存到redis缓存中。
        //需要设置过期时间吗? 否
        //不设置过期时间的：原因，由其他的业务来删除缓存
        // 用户手动取消订单或延迟消息15分钟处理未支付自动取消订单；  需要解锁库存  删掉缓存
        // 用户15分钟支付订单，  需要减库存  删掉缓存
        // 如果所有商品都锁定成功的情况下，需要缓存锁定信息到redis。以方便将来解锁库存 或者 减库存
        redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        //redisTemplate.delete(key); // ??????  不删除，继续VB保留，继续解决重试问题。
        return "";// 空就表示成功结果。
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unLock(String orderNo) {
        //1.去重 重复消息处理
        String key = "sku:unlock" + orderNo;
        String dataKey = "sku:lock:data" + orderNo; //业务完成，需要将锁定的数据保存到redis中时用到的key
        //业务去重，防止重复消费  //2.从缓存中把锁定数据获取到，并且校验是否为空
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!flag) {
            return;
        }
        // 获取锁定库存的缓存信息
        List<SkuLockVo> skuLockVos = (List<SkuLockVo>) this.redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuLockVos)) {
            return;
        }
        // 解锁库存
        skuLockVos.forEach(skuLockVo -> {
            int unlock = skuStockMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if (unlock == 0) {
                //解除去重
                this.redisTemplate.delete(key);
                throw new ServiceException("解锁库存失败");
            }
        });
        // 解锁库存之后，删除锁定库存的缓存。以防止重复解锁库存
        this.redisTemplate.delete(dataKey);
    }

    @Override
    public void minus(String orderNo) {
        String key="sku:unlock"+orderNo;
        String dataKey="sku:lock:data"+orderNo;
        //业务去重，防止重复消费
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (!flag) {
            return;
        }
        // 获取锁定库存的缓存信息
        List<SkuStockVo> skuStockVos = (List<SkuStockVo>) this.redisTemplate.opsForValue().get(dataKey);
        if (CollectionUtils.isEmpty(skuStockVos)) {
            return;
        }
        // 减库存
        skuStockVos.forEach(skuStockVo -> {
            //含消息去重处理   //扣减库存
            int minus = skuStockMapper.minus(skuStockVo.getSkuId(), skuStockVo.getSaleNum());
            if (minus==0) {
                //解除去重
                this.redisTemplate.delete(key);
                throw new ServiceException("扣减库存失败");
            }
        });
        // 解锁库存之后，删除锁定库存的缓存。以防止重复解锁库存
        this.redisTemplate.delete(dataKey);

    }
}
